package fr.lelouet.ga.utils;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;

/**
 * utility for manipulating sets.
 * @author le louet
 */
public class SetUtils {

  protected static Random ran = null;

  protected static void initRan() {
    if (SetUtils.ran == null) {
      SetUtils.ran = new Random();
    }
  }

  /**
   * select a random element from the set. Useful when you need several elements
   * from a set, and expect them to be different<br />
   * However, they are likely to be different, but difference between several
   * call is not ensure.
   * @param <T>
   *          elements contained in the set
   * @param set
   *          set to get a random element from
   * @return a randomly chosen element from set
   */
  public static <T> T getAny(Set<T> set) {
    SetUtils.initRan();
    int remaining = SetUtils.ran.nextInt(set.size());
    for (Iterator<T> it = set.iterator(); it.hasNext() && remaining >= 0; remaining--) {
      if (remaining == 0) {
        return it.next();
      } else {
        it.next();
      }
    }
    throw new NoSuchElementException();
  }

}
